package com.smarttiger.zero.admin.webservice;

import com.alibaba.fastjson.JSON;
import com.smarttiger.zero.admin.dao.*;
import com.smarttiger.zero.admin.entity.*;
import com.smarttiger.zero.admin.dao.*;
import com.smarttiger.zero.admin.entity.*;
import com.smarttiger.zero.admin.service.InterfaceService;
import com.smarttiger.zero.admin.service.LogsService;
import com.smarttiger.zero.admin.service.UsersService;
import com.smarttiger.zero.admin.util.Constant;
import com.smarttiger.zero.logic.ExecuteLogics;
import com.smarttiger.zero.logic.InterfaceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

@Component
public class AppServiceSpring {

    @Autowired
    LogsService logsService;

    @Autowired
    UsersService usersService;

    @Autowired
    private InterfaceService interfaceService;

    @Autowired
    InterfaceDao interfaceDao;

    @Autowired
    InterfaceUsersGroupDao interfaceUsersGroupDao;

    @Autowired
    WhiteListDao whiteListDao;

    @Autowired
    BlackListDao blackListDao;

    @Autowired
    InterfaceLogicDao interfaceLogicDao;

    @Autowired
    InterfaceArgsDao interfaceArgsDao;

    @Autowired
    LogicDao logicDao;

    public String api(String icode,String token, List<Object> argsList){
        ApiMessage message = new ApiMessage();
        InterfaceModel interfaceConfig = interfaceDao.findByCode(icode);
        if (interfaceConfig == null) {
            message.setCode("-1");
            message.setData("code不存在");
            return JSON.toJSONString(message);
        }
        if ("N".equals(interfaceConfig.getIsAlive())) {
            message.setCode("-1");
            message.setData("接口状态为不可用");
            return JSON.toJSONString(message);
        }
        UsersModel users = usersService.findByToken(token);
        if (users == null) {
            message.setCode("-1");
            message.setData("token错误");
            return JSON.toJSONString(message);
        }

        boolean isBlack = false;
        List<UsersModel> blacklistModels = blackListDao.queryBlackListModelByInterfaceId(interfaceConfig.getId());
        for (UsersModel blacklistModel : blacklistModels) {
            if (users.getId().equals(blacklistModel.getId())) {
                isBlack = true;
                break;
            }
        }
        if (isBlack) {
            message.setCode("-1");
            message.setData("接口无权限,请联系管理员！");
            return JSON.toJSONString(message);
        }

        boolean isOkUser = false;
        List<UsersGroupModel> usersGroupModels = interfaceUsersGroupDao.queryUserGroupListModelByInterfaceId(interfaceConfig.getId());
        for (UsersGroupModel usersGroupModel : usersGroupModels) {
            List<UsersModel> usersModelList = interfaceUsersGroupDao.queryUsersByGroupId(usersGroupModel.getId());
            boolean isHave = false;
            for (UsersModel usersModel : usersModelList) {
                if (users.getId().equals(usersModel.getId())) {
                    isHave = true;
                    break;
                }
            }
            if (isHave) {
                isOkUser = true;
                break;
            }
        }


        if (!isOkUser) {
            boolean isWhite = false;
            List<UsersModel> whitelistModels = whiteListDao.queryWhiteListModelByInterfaceId(interfaceConfig.getId());
            for (UsersModel whitelistModel : whitelistModels) {
                if (users.getId().equals(whitelistModel.getId())) {
                    isOkUser = true;
                    break;
                }
            }
        }

        if (!isOkUser) {
            message.setCode("-1");
            message.setData("接口无权限,请联系管理员。");
            return JSON.toJSONString(message);
        }

        Map paramMap = new HashMap();
        List<InterfaceArgsModel> argsModels = interfaceArgsDao.findAllByInterfaceId(interfaceConfig.getId());
        for(int i=0;i<argsModels.size();i++){
            InterfaceArgsModel argsModel = argsModels.get(i);
            Object param = argsList.get(i);
            //java类型
            if(param != null){
                paramMap.put(argsModel.getName(), param);
            }else if (!StringUtils.isEmpty(argsModel.getDefaultValue())) {
                paramMap.put(argsModel.getName(), TransferUtil.transferS2J(argsModel.getTypecode(),argsModel.getDefaultValue()));
            }else{
                paramMap.put(argsModel.getName(), null);
            }
        }

        Map<String, Object> currentValue = InterfaceContext.paramContext.get();
        if (currentValue == null) {
            currentValue = new HashMap<>();
            InterfaceContext.paramContext.set(currentValue);
        }
        currentValue.put(Constant.INTERFACECURRENT, paramMap);


        LogsModel logs = new LogsModel();
        logs.setStartDate(new Date());

        List<LogicModel> logicModels = logicDao.findLogicModelByInterfaceId(interfaceConfig.getId());
        if(logicModels.size()==0){
            message.setCode("-1");
            message.setData("逻辑块没有配置。");
            return JSON.toJSONString(message);
        }

        Object o = null;
        try {
            o = ExecuteLogics.executeLogics(logicModels);
            logs.setNote("调用成功");
        } catch (Exception e) {
            logs.setNote("调用失败");
            message.setCode("-1");
            message.setData("逻辑块类配置不正确。");
            return JSON.toJSONString(message);
        }finally {
            logs.setCode(icode);
            logs.setName(interfaceConfig.getName());
            logs.setEndDate(new Date());
            logs.setUsersId(users.getId());
            logs.setUsersName(users.getName());
            logsService.save(logs);
        }

        message.setCode("1");
        message.setData(o);
        String s = JSON.toJSONString(message);
        return s;
    }

}